class TemplateElement {
  final String id;
  final String type;
  final String? text; // 可为空
  final String? img; // 可为空
  final Style? style;

  TemplateElement({
    required this.id,
    required this.type,
    this.text,
    this.img,
    this.style,
  });

  factory TemplateElement.fromJson(Map<String, dynamic> json) {
    return TemplateElement(
      id: json['id'] ?? '',
      type: json['data-type'] ?? '',
      text: json['text'],
      img: json['img'],
      style: json['style'] != null ? Style.fromJson(json['style']) : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'type': type,
      if (text != null) 'text': text,
      if (img != null) 'img': img,
      if (style != null) 'style': style!.toJson(),
    };
  }
}

class Style {
  ///请使用px单位
  final int left;
  final int top;
  final int? width;
  final String? textAlign;
  final int? fontSize;
  final String? textColor;
  final String? fontFamily;

  Style({
    required this.left,
    required this.top,
    this.width,
    this.textAlign,
    this.fontSize,
    this.textColor,
    this.fontFamily,
  });

  factory Style.fromJson(Map<String, dynamic> json) {
    return Style(
      left: _parsePx(json['left']),
      top: _parsePx(json['top']),
      width: _parsePx(json['width']),
      textAlign: json['text-align'],
      fontSize: _parsePx(json['font-size']),
      textColor: _normalizeColor(json['color']),
      fontFamily: json['font-family'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'left': "${left}px",
      'top': "${top}px",
      if (width != null)'width': "${width}px",
      if (textAlign != null) 'text-align': textAlign,
      if (fontSize != null && fontSize! > 0) 'font-size': "${fontSize}px",
      if (textColor != null) 'color': textColor,
      if (fontFamily != null) 'font-family': fontFamily,
    };
  }

  static int _parsePx(String? value) {
    if (value == null) return 0;
    return double.tryParse(value.replaceAll('px', ''))?.toInt() ?? 0;
  }

  static String _normalizeColor(String color) {
    if (color.startsWith('#')) {
      return color; // 已经是 hex，直接返回
    }

    final regex = RegExp(r'rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+)\s*\)');
    final match = regex.firstMatch(color);
    if (match != null) {
      int r = int.parse(match.group(1)!);
      int g = int.parse(match.group(2)!);
      int b = int.parse(match.group(3)!);
      return '#${r.toRadixString(16).padLeft(2, '0')}'
          '${g.toRadixString(16).padLeft(2, '0')}'
          '${b.toRadixString(16).padLeft(2, '0')}';
    }
    return color;
  }
}

enum ElementType { image, text }
